package com.jkxt.controller;

import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jkxt.model.Users;
import com.jkxt.service.IUsersService;
import com.jkxt.tools.MD5;


/**
 * 用户登录 
 * @author LZ
 */
@Controller
public class UserLoginController {
	
	private IUsersService userSerivce;
	
	
	public IUsersService getUserSerivce() {
		return userSerivce;
	}
    @Autowired
	public void setUserSerivce(IUsersService userSerivce) {
		this.userSerivce = userSerivce;
	}

	@RequestMapping("/login")
	public String login(HttpServletRequest request){
		return "login";
	}
	
	
	/**
	 * 提交登陆信息  LZ
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String submitLogin(String name,String password,HttpServletRequest request){
		
		Users user= userSerivce.selectByNameService(name);
		
		if(user != null){
			if(!MD5.MD5(password).equals(user.getPassword())){
				request.setAttribute("message", "该用户未注册！");
				return "login";
			}
		}else{
			request.setAttribute("message", "该用户未注册！");
			return "login";
		}
		request.getSession().setAttribute("user", user);
		return "redirect:index/list.do";
	}
	
	/**
	 * 注册页面  LZ
	 * @return
	 */
	@RequestMapping("toUserRegister")
    public String toUserRegister(){
    	return "register";
    }
	
	/**
	 * 检查用户名是否重复 LZ
	 * @param name
	 * @param printWriter
	 * @param request
	 */
	@RequestMapping("checkUserName")
	public void checkUserName(String name,PrintWriter printWriter){
		Users user=userSerivce.selectByNameService(name);
		if(user==null){
			printWriter.write("success");
		}else {
			printWriter.write("error");
		}
		printWriter.flush();
		printWriter.close();
	}
	
	/**
	 * 注册用户
	 * @param name
	 * @param password
	 * @param email
	 * @param request
	 * @return
	 */
	@RequestMapping(value="saveRegister",method=RequestMethod.POST)
	public String saveRegister(String name,String password,String email,String sex,HttpServletRequest request){
		Users user=new Users();
		user.setName(name);
		user.setPassword(MD5.MD5(password));
		user.setEmail(email);
		user.setSex(sex);
		user.setCreateTime(new Date());
		int score= userSerivce.saveUserService(user);
		if(score > 0){
			return "redirect:login.do";
		}else {
			request.setAttribute("message", "注册失败!");
			return "redirect:toUserRegistert.do";
		}
		
	}

}
